<template>
  <!--  委外-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" label-width="auto" class="demo-form-inline">
        <el-form-item label="委外单号">
          <el-input v-model="searchParam.outsourcingNo" placeholder="请输入委外单号" clearable
                    style="width: 180px"/>
        </el-form-item>
        <el-form-item label="工序订单号">
          <el-input v-model="searchParam.procedureOrderNo" placeholder="请输入工序订单号" clearable style="width: 180px"/>
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input v-model="searchParam.supplierName" placeholder="请输入供应商名称" clearable
                    style="width: 180px"/>
        </el-form-item>
        <el-form-item label="物料编码">
          <el-input v-model="searchParam.materialNo" placeholder="请输入物料编码" clearable
                    style="width: 180px"/>
        </el-form-item>
        <el-form-item label="是否已入账">
          <el-select v-model="searchParam.recordedStatus" placeholder="请选择是否已入账" clearable style="width: 180px">
            <el-option v-for="item in recordedStatusOptions" :key="item.value" :label="item.label"
                       :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          <el-button class="refreshBtn" :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <div class="pageTableButView">
          <el-button icon="Download" type="primary" :loading="downLoading" @click="handleExport"
                     style="margin-left: 10px;">导出
          </el-button>
<!--          <el-button  type="primary"  :icon="Plus" @click="handleAdd()">新建</el-button>-->
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" height="calc(100vh - 320px)"
                header-cell-class-name="witheTableHeader">
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope">
            <!-- 下标 + 1，计算公式：当前页数 * 每页大小 + 当前行的索引 + 1 --> {{
              (pageSearch.current - 1) * pageSearch.pageSize
              + scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="outsourcingNo" label="委外单号" align="center" min-width="200"/>
        <el-table-column prop="procedureOrderNo" label="工序订单号" align="center" min-width="200"/>
        <el-table-column label="委外数量" align="center" prop="outsourcingCount" min-width="200"/>
<!--        <el-table-column prop="planCount" width="200" label="计划数量" align="center"/>-->
        <el-table-column prop="inStockCount" label="已回库数量" width="200" align="center"/>
        <el-table-column prop="returnCount" label="已退货数量" width="200" align="center"/>
        <el-table-column prop="rawCount" label="未加工数量" width="200" align="center"/>
        <el-table-column prop="attritionRateStr" label="损耗率" width="200" align="center"/>
        <el-table-column prop="recordedStatus" label="是否已入账" width="200" align="center">
          <template #default="scope">
            {{ scope.row.recordedStatus ? '已入账' : '未入账' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="单据状态" align="center" min-width="200">
          <template #default="scope">
            <span> {{ getQualityTypeByValue(scope.row.receiptsStatus) }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="demandTime" label="需求日期" min-width="180" align="center"/>
        <el-table-column prop="supplierName" label="供应商" align="center" min-width="250"/>
        <el-table-column prop="putWarehouseName" width="250" label="产品入库仓库" align="center"/>
        <!--				<el-table-column prop="supplierWarehoseName" width="250" label="供应商材料库" align="center" />-->
        <el-table-column prop="warehouseName" label="发货仓库" width="250" align="center"/>

        <el-table-column label="操作" align="center" fixed="right" width="200">
          <template #default="scope">
            <el-button
                @click="handleToggleRecorded(scope.row)"
                type="text"
                size="small"
                plain
                :icon="Edit">
              {{ scope.row.recordedStatus ? '取消入账' : '确认入账' }}
            </el-button>
            <!--									<el-button @click="handleDel(scope.row)" text type="danger" size="small" :icon="Delete">删除</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current"
                       v-model:page-size="pageSearch.pageSize" :page-sizes="[10, 20, 50, 100, 200, 500]"
                       layout="total, sizes, prev, pager, next" :total="pageTotal" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </div>
    <!-- 弹窗表单 -->
    <el-dialog v-model="showCrud" :title="crudTitle" width="95%" top="5vh">
      <el-form :model="formData" label-width="auto" ref="ruleFormRef" :rules="rules" class="demo-ruleForm">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="工序订单号" prop="procedureOrderId">
              <el-select v-model="formData.procedureOrderId" placeholder="请选择工单" filterable clearable
                         style="width: 300px" @change="workOrderChange" :disabled="!canEdit">
                <el-option v-for="(item, index) of workOrderList" :key="index" :label="item.no"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="formData.supplierId" placeholder="请选择供应商" remote
                         :remote-method="supplierSearch" filterable clearable :disabled="!canEdit" style="width: 300px">
                <el-option v-for="(item, index) of supplierList" :key="index" :label="item.name"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产出物料编号"> {{ formData.materialNo || '--' }}
              <!--							<el-select v-model="formData.workId" placeholder="请选择供应商" filterable clearable-->
              <!--												 style="width: 300px" @change="workOrderChange">-->
              <!--								<el-option v-for="(item,index) of workOrderList" :key="index" :label="item.workNo"-->
              <!--													 :value="item.id" />-->
              <!--							</el-select>-->
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="需求日期" prop="demandTime">
              <!--							<el-date-picker v-model="formData.demandTime" type="date" value-format="YYYY-MM-DD"-->
              <!--								placeholder="选择需求日期" />-->
              <el-date-picker
                  v-model="formData.demandTime"
                  type="datetime"
                  placeholder="选择需求日期"
                  value-format="YYYY-MM-DD hh:mm:ss"
                  :disabled="!canEdit"
                  style="width: 300px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品入库仓库" prop="putWarehouseId">
              <el-select v-model="formData.putWarehouseId" placeholder="请选择仓库" filterable clearable :disabled="!canEdit"
                         style="width: 300px">
                <el-option v-for="(item, index) of storageAllList" :key="index"
                           :label="item.storageName" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="供应商材料库" prop="supplierWarehoseId">
              <el-select v-model="formData.supplierWarehoseId" placeholder="请选择仓库" filterable clearable
                style="width: 300px">
                <el-option v-for="(item, index) of storageAllList" :key="index"
                  :label="item.storageName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item label="委外数量" prop="outsourcingCount">
              <el-input-number v-model="formData.outsourcingCount" :step="1" step-strictly :min="0" :disabled="!canEdit"
                               style="width: 300px"/>
            </el-form-item>
          </el-col>
          <!--					<el-col :span="6">-->
          <!--						<el-form-item label="附件上传">-->
          <!--							&lt;!&ndash;							<el-input-number v-model="formData.count" :step="1" step-strictly :min="0" style="width: 300px" />&ndash;&gt;-->
          <!--						</el-form-item>-->
          <!--					</el-col>-->
          <el-col :span="6">
            <el-form-item label="计划号">
              <el-input v-model="formData.planNo" disabled style="width: 300px" :disabled="!canEdit"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发货仓库" prop="warehouseId">
              <el-select v-model="formData.warehouseId" placeholder="请选择仓库" filterable clearable
                         :disabled="!formData.procedureOrderId || !canEdit"
                         style="width: 300px" @change="warehouseChange">
                <el-option v-for="(item, index) of storageAllList" :key="index"
                           :label="item.storageName" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="实际重量">
              <el-input v-model="formData.weight" style="width: 260px;margin-right: 8px" :disabled="!canEdit"/>
              KG
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注">
              <el-input v-model="formData.remark" style="width: 300px" :disabled="!canEdit"/>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="pageTableMenuView">
          <div class="pageTableTitle"> 物料明细</div>
          <div class="pageTableButView">

          </div>
        </div>
        <el-table class="pageTableClass" :data="workDetailData" border row-key="id" height="400px">
          <el-table-column label="序号" align="center" type="index" width="65"/>
          <el-table-column prop="name" label="物料" align="center" min-width="300">
            <template #default="scope" v-if="canEdit">
              <el-select v-model="scope.row.sourceId" placeholder="请选择物料" clearable filterable
                         style="width: 100%" :disabled="!canEdit" @change="detailMaterialChange(scope.$index)">
                <el-option v-for="item in materiaList" :key="item.id" :label="item.materialName"
                           :value="item.id">
                  <div style="display: flex;justify-content: flex-start;">
                    <div style="width: 180px;">{{ item.materialName }}</div>
                    <div
                        style="width: 180px; color: var(--el-text-color-secondary);font-size: 13px;">
                      {{ item.batchNo }}
                    </div>
                    <div
                        style="width: 100px; color: var(--el-text-color-secondary);font-size: 13px;">
                      数量：{{ item.count }}
                    </div>
                  </div>
                </el-option>
              </el-select>
            </template>

            <template #default="scope" v-else>
              {{ scope.row.materialName }}
            </template>
          </el-table-column>
          <el-table-column prop="traceabilityCodePlace" label="模具号" align="center" min-width="250"/>
          <el-table-column prop="traceabilityCode" label="追溯码" align="center"
                           min-width="250"></el-table-column>
          <el-table-column prop="materialBatchNo" label="批次号" align="center" min-width="250"/>
          <el-table-column prop="planCount" label="计划数量" align="center" min-width="180">
            <template #default="scope">
              <el-input-number v-model="scope.row.planCount" :min="0" @change="planCountChange" :disabled="!canEdit"/>
            </template>
          </el-table-column>
          <el-table-column prop="outCount" label="出库数量" align="center" min-width="180"/>
          <el-table-column prop="intCount" label="加工领料数量" align="center" min-width="180"/>
          <el-table-column prop="description" label="备注" align="center" min-width="250">
            <template #default="scope">
              <el-input v-model="scope.row.description" :disabled="!canEdit" clearable/>
            </template>
          </el-table-column>
          <!--					<el-table-column prop="name" label="创建人" align="center" min-width="120">-->
          <!--					</el-table-column>-->
          <!--					<el-table-column prop="name" label="创建时间" align="center" min-width="200">-->
          <!--					</el-table-column>-->
          <!--					<el-table-column prop="name" label="更新人" align="center" min-width="120">-->
          <!--					</el-table-column>-->
          <!--					<el-table-column prop="name" label="更新时间" align="center" min-width="200">-->
          <!--					</el-table-column>-->
          <!--					<el-table-column prop="planCount" label="物料版本" align="center" min-width="200">-->
          <!--						<template #default="scope">-->
          <!--							<el-input v-model="scope.row.planCount" clearable />-->
          <!--						</template>-->
          <!--					</el-table-column>-->
          <el-table-column label="操作" align="center" fixed="right" width="220" v-if="canEdit">

            <template #header="scope">
              <el-button type="text" size="small" :icon="Plus" @click="addWorkOrderDetail">新建</el-button>
            </template>
            <template #default="scope">
              <el-button @click="delWorkOrderDetail(scope.$index)" text type="danger" size="small"
                         :icon="Delete">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave(ruleFormRef)"

          >保存
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 驳回 -->
    <!-- 弹窗表单 -->
    <el-dialog v-model="showTurn" title="是否驳回" width="400" top="5vh">
      <el-form :model="turnFormData" ref="ruleFormRef" :rules="rulesIs" label-width="100px" class="demo-ruleForm">
        <el-row :gutter="10">
          <el-col :span="22">
            <el-form-item label="驳回单号" prop="rejectCode" required>
              <el-input
                  v-model="turnFormData.rejectCode"
                  placeholder="请输入驳回单号"
                  clearable
                  style="width: 300px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="驳回数量" prop="rejectCount" required>
              <el-input
                  v-model="turnFormData.rejectCount"
                  type="number"
                  placeholder="请输入驳回数量"
                  clearable
                  style="width: 300px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="驳回原因" prop="rejectCause" required>
              <el-input
                  v-model="turnFormData.rejectCause"
                  type="textarea"
                  placeholder="请输入驳回原因"
                  clearable
                  style="width: 300px"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showTurn = false">取消</el-button>
          <el-button type="primary" @click="turn">驳回</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {computed, getCurrentInstance, reactive, ref} from 'vue';
//弹出层标题
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage, ElMessageBox} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {Delete, Plus, Printer, Refresh, Search, Setting, Edit} from '@element-plus/icons-vue';
import moment from 'moment';
import axios from "axios";

onMounted(() => {
  getList();
  getOption();
});

// 切换入账状态
const handleToggleRecorded = (row: any) => {
  ElMessageBox.confirm(
      `确定设为${row.recordedStatus ? '未入账' : '已入账'}吗？`,
      '状态变更确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    // 创建更新对象
    const updateData = {
      id: row.id,
      recordedStatus: !row.recordedStatus
    }

    // 调用更新接口
    axiosInstance.put('/api/outsourcingPlan/updateRecordedStatus', updateData)
        .then(res => {
          if (res.code !== 200) {
            ElMessage.error(res.message);
            return;
          }
          ElMessage.success('状态更新成功！');
          getList(); // 刷新列表
        })
  }).catch(() => {
    // 取消操作
  });
};

const planCountChange = () => {
  // 初始值为 0
  formData.outsourcingCount = workDetailData.value.reduce((accumulator, currentElement) => {
    return accumulator + (currentElement.planCount || 0); // 如果 planCount 不存在，则默认为 0
  }, 0);
  // formData.value = param
};


const pageSearch = ref({
  current: 1,
  pageSize: 10
});

const configTableShow = ref(false);

const handleClick = (e) => {
  console.log(e, 'handleClick');
};
// 配置质检项表
const configTable = ref([]);

// 可适用物料
const materialTable = ref([]);


const rowInfo = ref({});
const showTurn = ref(false);

const workOrderList = ref({});

const showMaterial = ref(false);
// 质检列表
const isConfigEdit = ref(false);

const isConfigIndex = ref(null);
const recordedStatusOptions = ref([
  {label: '已入账', value: true},
  {label: '未入账', value: false}
]);
const operationStatus = ref([
  {label: '编辑', value: -1},
  {label: '确认', value: 0},
  {label: '取消', value: 4},
  {label: '强制完结', value: 5}
]);

const workDetailData = ref([{}]);
const generateOperationStatus = (status: number) => {
  let baseStatus = [

    {label: '确认', value: 0},
    {label: '取消', value: 4},
    {label: '强制完结', value: 5}
  ];

  if (status.status > 3) {
    return [{label: '查看', value: -1}, ...baseStatus];
  }


  return [{label: '编辑', value: -1}, ...baseStatus];
};


const workOrderChange = (e) => {
  // formData.supplierId = null;
  if (!e) {
    formData.materialNo = null;
    // formData.warehouseId = null;
    formData.materialId = null;
    formData.planNo = null;
    formData.planId = null;
    return false;
  }

  for (const item of workOrderList.value) {
    if (item.id == e) {
      formData.materialNo = item.materialNo;
      formData.materialId = item.materialId;
      formData.planNo = item.planNo;
      formData.planId = item.planId;
    }
  }
  axiosInstance.post('/api/materialSupplier/getPage', {materialId: formData.materialId, current: 1, pageSize: 10})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        if (!formData.supplierId) {
          formData.supplierId = res.data.records[0]?.supplierId;
        }
      });
};

const addWorkOrderDetail = () => {
  workDetailData.value.push({});
};


const delWorkOrderDetail = (e) => {
  workDetailData.value.splice(e, 1);
  planCountChange();
};


// 通用更新接口函数
const handleUpdateQualityScheme = (updatedRowInfo) => {
  axiosInstance.put('/api/basedataQualityScheme/update', updatedRowInfo).then(res => {
    if (res.code != 200) {
      ElMessage.error(res.message);
      return false;
    }
    ElMessage.success('操作成功!');
    showConfig.value = false;
    showMaterial.value = false;
    // 刷新配置质检项列表
    getList();
  });
};


const pageTotal = ref(null);//页面总数
// const formData = reactive({});//form表单
const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框
const searchParam = ref({});//页面检索条件
const showConfig = ref(false);
const configData = ref({});
const turnFormData = ref({});//form表单
const turnForm = ref({});//form表单
const crudTitle = computed(() => {
  return isEdit.value ? '编辑' : '新建';
});
const ruleFormRef = ref<FormInstance>();

const turn = () => {
  ruleFormRef.value?.validate((valid) => {
    if (valid) {
      const dataTurn = turnForm.value
      axiosInstance.post(`/api/outsourcingWorkMaterial/reject`, {

        id: dataTurn.id,
        rejectCount: turnFormData.value.rejectCount,
        rejectCause: turnFormData.value.rejectCause,
        rejectCode: turnFormData.value.rejectCode,

      }).then(res => {
        ElMessage.success('驳回成功');
        getList(); // 刷新数据
        showTurn.value = false
        turnForm.value = {}
      });

    } else {
      ElMessage.error('请填写完整表单');
    }
  });
};
// 质检方式
const qualityWayList = reactive([
  {
    label: '全检',
    value: '1'
  }, {
    label: '比例抽检',
    value: '2'
  }, {
    label: '固定抽检',
    value: '3'
  }, {
    label: '自定义抽检',
    value: '4'
  }
]);


// 判断质检类型
const getQualityTypeByValue = (e) => {
  let name = null;
  for (const item of qualityTypeList) {
    if (e == item.value) {
      name = item.label;
    }
  }
  return name;
};

// 质检类型
const qualityTypeList = reactive([
  {
    label: '强制完结',
    value: '5'
  },
  {
    label: '取消',
    value: '4'
  },
  {
    label: '新建状态',
    value: '3'
  },
  {
    label: '部分送货',
    value: '1'
  },
  {
    label: '全部送货',
    value: '2'
  },
  {
    label: '未送货',
    value: '0'
  }
  // 继续添加更多检查类型...
]);


interface RuleForm {
  name: string;
  code: string;
  qualityWay: string;
  proportionNumber: string;
  qualityNumber: string;
  qualityType: string;
  qualityInterval: number;
  qualityIsLive: boolean;
  qualityRemark: string;
}


const originalFormData = reactive<RuleForm>({
  name: '',
  code: '',
  qualityWay: null,
  proportionNumber: 1,
  qualityNumber: 1,
  qualityType: '',
  qualityInterval: 1,
  qualityIsLive: true,
  qualityRemark: ''
});

let formData = reactive<RuleForm>(originalFormData);


const rules = reactive<FormRules<formData>>({
  workId: [
    {required: true, message: '请选择工序订单号', trigger: 'blur'}
  ],
  supplierId: [
    {required: true, message: '请选择供应商', trigger: 'blur'}
  ],
  demandTime: [
    {required: true, message: '请选择需求日期', trigger: 'blur'}
  ],
  putWarehouseId: [
    {required: true, message: '请选择产品入库仓库', trigger: 'blur'}
  ],
  supplierWarehoseId: [
    {required: true, message: '请选择供应商材料库', trigger: 'blur'}
  ],
  outsourcingCount: [
    {required: true, message: '请填写委外数量', trigger: 'blur'}
  ],
  warehouseId: [
    {required: true, message: '请选择发货仓库', trigger: 'blur'}
  ],
  procedureOrderId: [
    {required: true, message: '请选择工序订单号', trigger: 'blur'}
  ]
});

const rulesIs = reactive<FormRules<typeof turnFormData>>({
  rejectCode: [
    {required: true, message: '请输入驳回单号', trigger: 'blur'}
  ],
  rejectCount: [
    {required: true, message: '请输入驳回数量', trigger: 'blur'}
  ],
  rejectCause: [
    {required: true, message: '请输入驳回原因', trigger: 'blur'}
  ],

});


const downLoading = ref(false);
const handleExport = () => {
  downLoading.value = true;
  axios.post('/api/outsourcingPlan/getReportStockExportExcel', {
    ...searchParam.value
  }, {
    timeout: 30000, // 与 axiosInstance 的 timeout 相同
    responseType: 'blob',
    headers: {
      BearerToken: localStorage.getItem('token') || undefined // 与请求拦截器中的设置相同
    }
  })
      .then(response => {
        console.log(response);
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        const formattedDate = moment().format('YYYYMMDD');
        link.setAttribute('download', '委外库存报表' + formattedDate + '.xlsx'); // 导出的格式一定要和接口返回的文件一致
        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
      })
      .finally(() => {
        downLoading.value = false;
      });
};


// const paginatedData = reactive([])//列表数据
const paginatedData = ref<RuleForm[]>([]);

const materiaList = ref([]);//物料表
const wareList = ref([]);//仓库
const procedureOrderList = ref([]);//工序订单
const supplierList = ref([]);
const storageAllList = ref([]);
// 供应商远端搜索
const supplierSearch = async (query: string) => {
  if (query) {
    try {
      const response = await axiosInstance.post(`/api/basedataSupplier/getPage`, {
        current: 1,
        pageSize: 20,
        name: query
      });
      supplierList.value = await response.data.records; // 假设返回的数据直接是供应商列表
    } catch (error) {
      supplierList.value = []; // 出错时清空列表
    }
  }
};

const recall = (row) => {
  turnFormData.value = {
    id: '',
    rejectCount: '',
    rejectCause: '',
    rejectCode: '',
  }
  showTurn.value = true
  turnForm.value = row
  // ElMessageBox.confirm('确定驳回该条记录吗？', '提示', {
  // 	confirmButtonText: '确定',
  // 	cancelButtonText: '取消',
  // 	type: 'warning'
  // }).then(async () => {
  // 	axiosInstance.post(`/api/outsourcingWorkMaterial/reject`, {

  // 	...row

  // 	}).then(res => {
  // 		ElMessage.success('驳回成功');
  // 		getList(); // 刷新数据
  // 	});


  // });
}
const canEdit = ref(true);//true可以编辑
const operationStatusChange = (row, itemValue) => {
  canEdit.value = true;
  if (itemValue.value === -1 || itemValue.value === -2) {
    if (itemValue.value === -2) {
      canEdit.value = false;
    }
    handleEdit(row);
    return;
  }
  let httpsUrl = '';
  if (itemValue.value === 0) {
    httpsUrl = '/api/outsourcingPlan/verifySource';
  } else if (itemValue.value === 4) {
    httpsUrl = '/api/outsourcingPlan/cancelSource';
  } else {
    httpsUrl = '/api/outsourcingPlan/forcedCompletion';
  }
  ElMessageBox.confirm(
      `是否更改状态为${itemValue.label}`,
      ``,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消'

      }
  )
      .then(() => {
        axiosInstance.post(httpsUrl, {
          ...row,
          status: itemValue.value
        })
            .then(res => {
              if (res.code !== 200) {
                ElMessage.error(res.message);
                return false;
              }
              ElMessage.success('更改成功');
              getList();
            });
      })
      .catch(() => {

      });
};

const getOption = () => {
  axiosInstance.post('/api/outsourcingPlan/querySourcingPlanProcedureOrder', {})
      .then(res => {
        workOrderList.value = res.data;
      });

  // 查询所有库位
  axiosInstance.post('/api/basedataStorage/getAll', {})
      .then(res => {
        storageAllList.value = res.data;
      });


  axiosInstance.post(`/api/basedataSupplier/getPage`, {
    current: 1,
    pageSize: 20
  }).then(res => {
    if (res.code == 200) {
      supplierList.value = res.data.records;
    }
  });
  // axiosInstance
  // 	.post('/api/basedataMaterial/getAll', {}).then(res => {
  // 	if (res.code == 200) {
  // 		const list = res.data;
  // 		const loop = [];
  // 		for (const item of list) {
  // 			loop.push(
  // 				{
  // 					value: item.id,
  // 					label: item.materialName
  // 				}
  // 			);
  // 		}
  // 		materiaList.value = loop;
  // 	}
  // });
  axiosInstance.post('/api/planProcedureOrder/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        const list = res.data;
        const loop = [];
        for (const item of list) {
          loop.push(
              {
                value: item.id,
                label: item.materialName
              }
          );
        }
        procedureOrderList.value = list;
      });

  axiosInstance.get('/api/basedataWarehouse/treeList', {}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    wareList.value = res.data;
  });
};

const warehouseChange = (e) => {
  axiosInstance.post('/api/warehouseStorageMaterial/queryByWarehouseId', {
    storageId: e,
    materialStatus: 1,
    procedureOrderId: formData.procedureOrderId
  })
      .then(res => {
        materiaList.value = res.data;
      });
};

const detailMaterialChange = (e) => {
  for (const item of materiaList.value) {
    if (item.id == workDetailData.value[e].sourceId) {
      workDetailData.value[e].traceabilityCode = item.traceabilityCode;
      // workDetailData.value[e].traceabilityCodePlaceIndex = item.traceabilityCodePlaceIndex;
      workDetailData.value[e].traceabilityCodePlace = item.traceabilityCodePlaceIndex;
      workDetailData.value[e].materialBatchNo = item.batchNo;
      workDetailData.value[e].materialId = item.materialId;
      workDetailData.value[e].planCount = item.count;
      workDetailData.value[e].description = item.reportWorkRecordDescription;
    }
  }
  planCountChange();
};


// 获取列表接口
const getList = () => {
  axiosInstance.post('/api/outsourcingPlan/getReportStockPage', {
    ...searchParam.value,
    ...pageSearch.value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        // const list = res.data.records;
        // for (const item of list) {
        //   item.children = item.outsourcingWorkMaterialVOS;
        // }
        paginatedData.value = res.data.records;
        pageTotal.value = res.data.total;
      });
};

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  getList();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  getList();
};

// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  pageSearch.value.current = 1;
  // current.value = 1
  getList();
};

// 点击新建
const handleAdd = () => {
  isEdit.value = false;
  canEdit.value = true;
  // ruleFormRef.value.resetFields()
  formData = reactive({});
  formData.demandTime = moment()
      .add(0, 'days')
      .format('YYYY-MM-DD HH:mm:ss');
  workDetailData.value = [{}];
  showCrud.value = true;
};

// 编辑
const handleEdit = (row: any) => {
  // console.log(row, 'row');
  // editList.value = row;
  isEdit.value = true;
  for (const key in row) {
    formData[key] = row[key];
  }
  console.log(formData, 'formData');
  workOrderChange(formData.procedureOrderId);
  warehouseChange(formData.warehouseId);
  workDetailData.value = formData.outsourcingWorkMaterialVOS;
  showCrud.value = true;
};

const {proxy}: any = getCurrentInstance();
const handlePrint = (item) => {
  const templateName = 'test_print1/OutsourcePlanPrint.cpt';
  proxy.$printClick(templateName, [item]);
};

// 删除记录
const handleDel = (row: any) => {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    axiosInstance.delete(`/api/outsourcingPlan/delete`, {
      data: {
        ids: [row.id]
      }
    }).then(res => {
      ElMessage.success('删除成功');
      getList(); // 刷新数据
    });


  });
};


// 弹框确定 确认新建 确定编辑
const handleSave = async (e: FormInstance | undefined) => {
  if (!e) return;
  await e.validate((valid, fields) => {
    if (valid) {
      for (const item of workDetailData.value) {
        if (!item.materialId) {
          ElMessage.error('请选择物料');
          return false;
        }
        if (!item.planCount || item.planCount == 0) {
          ElMessage.error('请输入计划数量');
          return false;
        }
        item.workId = formData.workId;
        item.outsourcingId = formData.procedureOrderId;
      }
      if (isEdit.value) {
        // 编辑
        axiosInstance.put('/api/outsourcingPlan/update', formData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          getList(); // 刷新数据
        });
      } else {
        // 新建
        formData.outsourcingWorkMaterialDTOS = workDetailData.value;
        axiosInstance.post('/api/outsourcingPlan/pullSource', formData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          getList(); // 刷新数据
        });
      }

    }
  });
};


// 模拟 API 调用
const addEquipment = async (data: any) => {
  // 假设这里有一个新建接口
  console.log('新建设备数据:', data);
};

const updateEquipment = async (data: any) => {
  // 假设这里有一个更新接口
  console.log('更新设备数据:', data);
};

const deleteEquipment = async (id: string) => {
  // 假设这里有一个删除接口
  console.log('删除设备ID:', id);
};
</script>
<style scoped>
.content {
}
</style>
